package com.optitronics.validators;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;

import com.optitronics.beans.ShoppingCartItem;
import com.optitronics.util.OptitronicsConstants;
import com.optitronics.util.OptitronicsUtils;

@Component
public class ShoppingCartValidator {

	private Log logger = LogFactory.getLog(this.getClass());

	/**
	 * Validates new shopping cart item
	 * 
	 * @param item
	 */
	public void validateNewItem(ShoppingCartItem item, Errors errors) {

		logger.info(OptitronicsUtils.getLoggerPrefix() + ": " + "Validating new ShoppingCartItem ");
		if (!OptitronicsUtils.validateEmail(item.getBuyerEmail())) {
			errors.rejectValue("buyerEmail", "field_invalid_email");
		}
		byte[] fileContent = {};
		try {
			fileContent = item.getFile().getBytes();
		} catch (IOException e) {
			logger.warn("Greska prilikom povlacenja sadrzaja fajla", e);
		}
		if (OptitronicsConstants.ORDER_TYPE_RENEWAL.equals(item.getOrderType()) && fileContent.length == 0) {
			errors.rejectValue("file", "field_file_required");
		}

		// Product product = Product.findProduct(item.getProductId());

	}
}
